package com.baidu.manager.modules.api.intercept;

import com.baidu.manager.common.exception.JqlException;
import com.baidu.manager.modules.annotation.Login;
import com.baidu.manager.modules.api.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: jql
 * @description: TODO(api 拦截)
 * @Date: Created by 16:13 2018/6/14
 */
@Component
public class ApiInterceptor extends HandlerInterceptorAdapter{

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }
        if (annotation == null){
            return true;
        }

        //获取token
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }

        //校验token
        if (StringUtils.isBlank(token)){
            throw new JqlException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }
        Claims claims = jwtUtils.getClaimByToke(token);
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
            throw new JqlException(jwtUtils.getHeader() + "已经失效", HttpStatus.UNAUTHORIZED.value());
        }
        return true;
    }
}
